import { shopmanager } from "proto-ts/shopmanager/product";
import { credentials } from "@grpc/grpc-js";
import { Service } from "typedi";
import { GRPC_ADDRESS } from "config/config";
import { setReqHeader, REPO_ERR, RES_INFO } from "config/const";
import { HttpParams } from "client/configVo";

const conn = new shopmanager.ProductServiceClient(
  GRPC_ADDRESS,
  credentials.createInsecure()
);
const textDecoder = new TextDecoder();
export const REPO_GOODS_INTERFACE = "repoGoodsInterface";

export interface goodsEntity {
  ID: number; // 唯一ID
  CreatedAt?: string; // 创建时间
  UpdatedAt?: string; // 更新时间
  DeletedAt?: string; // 删除时间
  OrganizationID?: number; // 关联组织ID
  AccountID?: number; // 关联账户ID
}

export interface accountEntity {
  Type?: string;
  UID?: string;
}

export interface repoGoodsInterface {
  getGoods(opts: HttpParams): Promise<goodsEntity | any>; // 从独立站获取商品列表
  getTotal(opts: HttpParams): Promise<goodsEntity | any>;
  hidden(opts: HttpParams): Promise<goodsEntity | any>;
  delete(opts: HttpParams): Promise<goodsEntity | any>;
  get_sku(opts: HttpParams): Promise<goodsEntity | any>;
  update_white(opts: HttpParams): Promise<goodsEntity | any>;
}

@Service(REPO_GOODS_INTERFACE)
class repo implements repoGoodsInterface {
  // 获取商品列表
  getGoods(opts: HttpParams): Promise<any> {
    const { request, response, userInfo } = opts;
    const header = setReqHeader(userInfo);
    const query = request.body.listParams;
    return new Promise<any>((resolve, reject) => {
      conn.List(
        new shopmanager.ListProductParam(query),
        header,
        (err, resp) => {
          if (err) return resolve(REPO_ERR(err, "获取商品列表"));
          const setting = <any>resp?.toObject();
          setting?.list?.forEach((item: any) => {
            if (!item.meta) return;
            item.meta = JSON.parse(textDecoder.decode(item.meta));
          });
          resolve(
            RES_INFO({
              data: {
                list: setting?.list || [],
                total: setting?.total || 0,
              },
            })
          );
        }
      );
    });
  }

  // 获取上架状态统计个数
  getTotal(opts: HttpParams): Promise<goodsEntity | any> {
    const { request, response, userInfo } = opts;
    const header = setReqHeader(userInfo);
    const query = request.body.totalParams;
    return new Promise<goodsEntity | any>((resolve, reject) => {
      conn.GetPublishStatusCount(
        new shopmanager.QueryProductParam(query),
        header,
        (err, resp) => {
          if (err) return resolve(REPO_ERR(err, "获取上架状态统计个数"));
          const setting = <any>resp?.toObject();
          resolve(
            RES_INFO({
              data: {
                list: setting?.list || [],
                total: setting?.total || 0,
              },
            })
          );
        }
      );
    });
  }

  // 批量隐藏
  hidden(opts: HttpParams): Promise<goodsEntity | any> {
    const { request, response, userInfo } = opts;
    const header = setReqHeader(userInfo);
    const query = request.body;
    return new Promise<goodsEntity | any>((resolve, reject) => {
      conn.BatchUpdateHiddenStatus(
        new shopmanager.BatchUpdateProductHiddenStatusParam(query),
        header,
        (err, resp) => {
          if (err) return resolve(REPO_ERR(err, "批量隐藏"));
          const setting = <goodsEntity>resp?.toObject();
          resolve(RES_INFO({ data: setting }));
        }
      );
    });
  }

  // 批量下架
  delete(opts: HttpParams): Promise<goodsEntity | any> {
    const { request, response, userInfo } = opts;
    const header = setReqHeader(userInfo);
    const query = request.body;
    return new Promise<goodsEntity | any>((resolve, reject) => {
      conn.BatchUpdatePublishStatus(
        new shopmanager.BatchUpdateProductPublishStatusParam(query),
        header,
        (err, resp) => {
          if (err) return resolve(REPO_ERR(err, "批量下架"));
          const setting = <goodsEntity>resp?.toObject();
          resolve(RES_INFO({ data: setting }));
        }
      );
    });
  }

  // 获取sku信息
  get_sku(opts: HttpParams): Promise<goodsEntity | any> {
    const { request, response, userInfo } = opts;
    const header = setReqHeader(userInfo);
    const query = request.query;
    return new Promise<goodsEntity | any>((resolve, reject) => {
      conn.GetSKU(
        new shopmanager.ProductIDParam(query),
        header,
        (err, resp) => {
          if (err) return resolve(REPO_ERR(err, "获取sku信息"));
          const setting: any = <goodsEntity>resp?.toObject();
          resolve(RES_INFO({ data: setting?.list || [] }));
        }
      );
    });
  }

  // 批量更新产品是否在白名单  id?: number;  in_whitelist?: boolean;
  update_white(opts: HttpParams): Promise<goodsEntity | any> {
    const { request, response, userInfo } = opts;
    const header = setReqHeader(userInfo);
    const query = request.body || [];
    return new Promise<goodsEntity | any>((resolve, reject) => {
      conn.BatchUpdateWhiteList(
        new shopmanager.BatchUpdateProductWhitelistParam({
          list: query.map((item: any) => {
            return new shopmanager.ProductWhitelistParam(item);
          }),
        }),
        header,
        (err, resp) => {
          if (err) return resolve(REPO_ERR(err, "批量更新产品是否在白名单"));
          const setting = <goodsEntity>resp?.toObject();
          resolve(RES_INFO({ data: setting }));
        }
      );
    });
  }
}
